package com.bsoft.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView tv_one;
    TextView tv_two;
    TextView tv_three;
    Intent intent;

    //本地广播
    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_one = (TextView) findViewById(R.id.tv_one);
        tv_two = (TextView) findViewById(R.id.tv_two);
        tv_three = (TextView) findViewById(R.id.tv_three);
        tv_one.setOnClickListener(this);
        tv_two.setOnClickListener(this);
        tv_three.setOnClickListener(this);

        localBroadcastManager=LocalBroadcastManager.getInstance(this);
        //新建intentFilter并给其action标签赋值。
        intentFilter=new IntentFilter();
        intentFilter.addAction("com.bsoft.broadcasttest.LOCAL_BROADCAST");

        //创建广播接收器实例，并注册。将其接收器与action标签进行绑定。
        localReceiver=new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_one:
                intent = new Intent("com.bsoft.broadcasttest.CLOCK");
                intent.putExtra("data", "Ding Ding 起床了!!!!");
                sendBroadcast(intent);
                break;
            case R.id.tv_two:
                intent = new Intent("com.bsoft.broadcasttest.ACTION");
                Bundle bundle=new Bundle();
                bundle.putString("data", "孩子们快起床");
                intent.putExtras(bundle);
                //有序广播
                sendOrderedBroadcast(intent, null);
                break;
            case R.id.tv_three:
                intent=new Intent("com.bsoft.broadcasttest.LOCAL_BROADCAST");
                //发送本地广播。
                localBroadcastManager.sendBroadcast(intent);
                break;
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        //取消注册调用的是unregisterReceiver()方法，并传入接收器实例。
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

    class  LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent){
            Toast.makeText(context,"这是本地广播接收器",Toast.LENGTH_SHORT).show();
        }
    }
}
